(in-package :gwee)

(defvar *font-cache* nil)

(defvar *default-font-name* nil
  "This must be supplies by the program through with-gui.")

(defvar *default-font-size* nil
  "This must be supplies by the program through with-gui.")

(defun default-font (&optional (size *default-font-size*))
  (open-font *default-font-name* size))

(defun init-fonts (font-name font-size)
  ;; (unless (sdl-ttf:is-init)
  ;;   (sdl-ttf:init-ttf))
  (setf *font-cache* (make-hash-table :test 'equal)
	*default-font-name* font-name
	*default-font-size* font-size))

(defun open-font (filename size)
  (let ((font (or (gethash (list filename size)
                           *font-cache*)
                  (setf (gethash (list filename size)
                                 *font-cache*)
                        ;; try to be smart about locating the file
                        (sdl::open-font (make-instance 'sdl:ttf-font-definition
                                                       :filename (namestring (or (probe-file filename)
                                                                                 (probe-file (resource filename))
                                                                                 (probe-file (relative-pathname filename))
                                                                                 (error "Cannot find font ~a ~a" filename size)))
                                                       :size size))))))
    (unless font
      (error "Cannot open font ~a ~a" filename size))
    font))

(defun string-width (string font)
  (sdl:get-font-size string :size :w :font font))
